<template>
  <div class="UserTable-container">
    <div class="filter-container">
      <el-input v-model="listQuery.username"
                :placeholder="$t('profile.username')|uppercaseFirst"
                style="width: 160px;"
                class="filter-item"
                @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.name"
                :placeholder="$t('profile.name')|uppercaseFirst"
                style="width: 160px;"
                class="filter-item"
                @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.role"
                 :placeholder="$t('profile.role')|uppercaseFirst"
                 clearable
                 style="width: 90px"
                 class="filter-item">
        <el-option v-for="item in roleOptions"
                   :key="item"
                   :label="item"
                   :value="item" />
      </el-select>
      <el-select v-model="listQuery.order"
                 style="width: 140px"
                 :placeholder="$t('profile.order')|uppercaseFirst"
                 class="filter-item"
                 @change="handleFilter">
        <el-option v-for="item in sortOptions"
                   :key="item.key"
                   :label="item.label"
                   :value="item.key" />
      </el-select>
      <el-button v-waves
                 class="filter-item"
                 type="primary"
                 icon="el-icon-search"
                 @click="handleFilter">
        {{$t('common.search')}}
      </el-button>
      <el-button class="filter-item"
                 style="margin-left: 10px;"
                 type="primary"
                 icon="el-icon-edit"
                 @click="handleCreate">
        {{$t('common.add')}}
      </el-button>
    </div>

    <el-table :key="tableKey"
              v-loading="listLoading"
              :data="list"
              border
              fit
              highlight-current-row
              style="width: 100%;">
      <el-table-column :label="$t('profile.createTime')|uppercaseFirst"
                       prop="createTime"
                       align="center">
        <template slot-scope="{row}">
          <!-- <span>{{ row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span> -->
          <span>{{ row.createTime | removeT()}}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('profile.username')|uppercaseFirst"
                       prop="username"
                       align="center">
        <!-- :class-name="getSortClass('id')"> -->
        <template slot-scope="{row}">
          <span>{{ row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('profile.name')|uppercaseFirst"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('profile.role')|uppercaseFirst"
                       align="center">
        <template slot-scope="scope">
          <el-tag effect="dark"
                  :type="filterItem(scope.row.role)"
                  disable-transitions>{{scope.row.role}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column :label="$t('common.action')"
                       align="center"
                       :col=6
                       class-name="small-padding fixed-width">
        <!-- <template slot-scope="{row,$index}"> -->
        <template slot-scope="{row}">
          <el-button type="primary"
                     size="mini"
                     @click="handleUpdate(row)">
            {{$t('common.edit')|uppercaseFirst}}
          </el-button>

          <el-button v-if="row.status!='deleted'"
                     size="mini"
                     type="danger"
                     @click="deleteUser(row)">
            {{$t('common.delete')|uppercaseFirst}}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0"
                :total="total"
                :page.sync="listQuery.page"
                :limit.sync="listQuery.limit"
                @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]"
               :visible.sync="dialogFormVisible">
      <el-form ref="dataForm"
               :rules="rules"
               :model="temp"
               label-position="left">
        <el-form-item :label="$t('profile.username')|uppercaseFirst"
                      prop="username">
          <el-input v-model="temp.username" />
        </el-form-item>
        <el-form-item :label="$t('profile.name')|uppercaseFirst"
                      prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item :label="$t('profile.newPassword')|uppercaseFirst"
                      v-if="dialogStatus==='create'"
                      prop="password">
          <el-input v-model="temp.password" />
        </el-form-item>
        <el-form-item :label="$t('profile.role')|uppercaseFirst">
          <el-radio v-model="temp.role"
                    label="admin">{{$t('common.admin')}}</el-radio>
          <el-radio v-model="temp.role"
                    label="editor">{{$t('common.editor')}}</el-radio>
          <el-radio v-model="temp.role"
                    label="visitor">{{$t('common.visitor')}}</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{$t('common.cancel')}}

        </el-button>
        <el-button type="primary"
                   @click="dialogStatus==='create'?createUser():updateUser()">
          {{$t('common.confirm')}}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { fetchList, createUser, updateUser, deleteUser } from '@/api/user'
import waves from '@/directive/waves' // waves directive
// import { removeT } from '@/utils'
// import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
export default {
  name: 'UserTable',

  computed: {
    ...mapGetters(['name'])
  },
  components: { Pagination },
  directives: { waves },
  data() {
    const validateUsername = (rule, value, callback) => {
      console.log(value)
      if (value === undefined) {
        callback(new Error(this.$t('profile.validate.username.null')))
      } else if (value.toString().length < 5 || value.toString().length > 18) {
        callback(new Error(this.$t('profile.validate.username.wrong')))
      } else {
        callback()
      }
    }
    const validateName = (rule, value, callback) => {
      if (value === undefined) {
        callback(new Error(this.$t('profile.validate.name.null')))
      } else if (value.toString().length < 2) {
        callback(new Error(this.$t('profile.validate.name.wrong')))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value === undefined) {
        callback(new Error(this.$t('profile.validate.password.null')))
      } else if (value.toString().length < 5 || value.toString().length > 18) {
        callback(new Error(this.$t('profile.validate.password.wrong')))
      } else {
        callback()
      }
    }
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        sort: 'createTime',
        order: undefined,
        role: undefined,
        username: undefined
      },
      roleOptions: ['admin', 'editor', 'visitor'],
      sortOptions: [
        { label: this.$t('profile.order_asc'), key: 'asc' },
        { label: this.$t('profile.order_desc'), key: 'desc' }
      ],
      temp: {
        name: undefined,
        username: undefined,
        password: undefined,
        role: 'admin'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: this.$t('common.modify'),
        create: this.$t('common.add')
      },
      rules: {
        username: [
          { required: true, validator: validateUsername, trigger: 'blur' }
        ],
        name: [{ required: true, validator: validateName, trigger: 'blur' }],
        password: [
          { required: true, validator: validatePassword, trigger: 'blur' }
        ]
      },
      downloadLoading: false
    }
  },
  filters: {
    Time(value) {
      var date = value.createTime.replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
      return date
    }
  },
  created() {
    this.getList()
  },
  // mounted() {
  //   setTimeout(() => {
  //     console.log(this.list)
  //   }, 1000)
  // },
  methods: {
    getList() {
      this.listLoading = false
      fetchList(this.listQuery).then(response => {
        console.log(response)
        this.list = response.data.items
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    resetListQuery() {
      this.listQuery = {
        sort: undefined,
        order: undefined,
        role: undefined,
        username: undefined
      }
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        name: undefined,
        username: undefined,
        role: 'admin'
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createUser() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          createUser(tempData).then(data => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: this.$t('profile.handle.create.success'),
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      console.log(row)
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    updateUser() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateUser(tempData).then(data => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: this.$t('profile.handle.update.success'),
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    deleteUser(row) {
      this.temp = Object.assign({}, row) // copy obj
      deleteUser(this.temp).then(data => {
        this.dialogFormVisible = false
        this.$notify({
          title: 'Success',
          message: this.$t('profile.handle.delete.success'),
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    },

    // formatJson(filterVal) {
    //   return this.list.map(v =>
    //     filterVal.map(j => {
    //       if (j === 'createTime') {
    //         return removeT(v[j])
    //       } else {
    //         return v[j]
    //       }
    //     })
    //   )
    // },

    getSortClass: function(key) {
      console.log(key)
      const order = this.listQuery.order
      return order === `+${key}` ? 'ascending' : 'descending'
    },
    filterItem(item) {
      console.log(item)
      if (item === 'admin') {
        return 'success'
      } else if (item === 'editor') {
        return 'warning'
      } else if (item === 'visitor') {
        return 'info'
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.UserTable {
  position: relative;
  width: 100%;
  height: calc(100vh - 84px);
}
</style>
